import { PayList } from "~~/types/payChannel";

export const channelDiscount = (pay: PayList, t: any) => {
  if (pay.preferentialType == 1) {
    if (pay.discountType == 2) {
      const discount = isNaN(Number(pay.discount))
        ? 0
        : Number(pay.discount) * 100;

      return `${t("live_recharge.discount")} ` + discount + "%";
    } else if (pay.discountType == 1) {
      return `${t("live_recharge.randomDiscount")} $0-$` + pay.discountRange;
    } else {
      return `${t("live_recharge.discount")} $` + pay.discount;
    }
  } else if (pay.preferentialType == 2) {
    if (pay.addMoneyType == 2) {
      const addMoney = isNaN(Number(pay.addMoney))
        ? 0
        : Number(pay.addMoney) * 100;

      return `${t("live_recharge.highest")} ` + addMoney + "%";
    } else if (pay.addMoneyType == 1) {
      return `${t("live_recharge.random")} $0-$` + pay.addMoneyRange;
    } else {
      return `${t("live_recharge.highest")} $` + pay.addMoney;
    }
  }

  return "";
};

// 固定值和 随机都是传  匹配到阶梯的  preferential 这个值
// 百分比类型是  要  preferential * 订单金额
export const getPreferentialAmount = (
  pay: PayList,
  amount: number | string
): string => {
  try {
    // 无优惠
    if (pay.preferentialType == 0) return "0";

    // 分组
    const firstPreferentialList =
      pay.preferentialList?.filter((item) => item.category === 0) ?? [];
    let secondPreferentialList =
      pay.preferentialList?.filter((item) => item.category === 1) ?? [];
    // 排序
    secondPreferentialList = secondPreferentialList.sort(
      (a, b) => Number(b.amount) - Number(a.amount)
    );

    // 固定或者随机
    let addMoney = firstPreferentialList.find((item) => item.amount == amount);

    // 如果没有匹配到，就取最大的
    if (!addMoney) {
      addMoney = secondPreferentialList.find(
        (item) => Number(amount) >= Number(item.amount)
      );
    }

    // 如果为空，就返回0
    if (isNaN(Number(addMoney?.preferential))) {
      return "0";
    }

    const preferential = isNaN(Number(addMoney?.preferential))
      ? 0
      : Number(addMoney?.preferential);

    if (addMoney?.type == 2) {
      return getFixed(`${preferential * Number(amount)}`);
    }

    return getFixed(preferential.toString());
  } catch (error) {
    return "0";
  }
};

// 截断 保留两位小数，如果小于0.01 就返回0.01
export const getFixed = (value: number | string): string => {
  // 不四舍五入
  const fixed = value.toString().match(/^\d+(?:\.\d{0,2})?/)?.[0] ?? "0";

  const val = Number(fixed) < 0.01 ? "0.01" : fixed;

  return isNaN(Number(val)) ? "0" : val;
};
